<script lang="ts" setup>
  import useTable from '@/hooks/table';
  import { User } from '@/types/user';
  import { Game, GameSignImportItem } from '@/types/game';
  import { onMounted, ref } from 'vue';
  import {
    getGamePlayerList,
    exportGamePlayer,
    deleteManualGameEnroll,
  } from '@/api/game';
  import dayjs from 'dayjs';
  import { Modal, Notification } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  import UnrealPlayerAdder from '@/views/game/components/unreal-player-adder.vue';
  import GameSignImport from './game-sign-import.vue';
  import GameSignManual from './game-sign-manual.vue';
  import GameSignImportResult from './game-sign-import-result.vue';
  import GameSignImportCustomer from './game-sign-import-customer.vue';

  const props = defineProps<{
    game: Game;
    gameId: string;
    isParentGame?: boolean;
  }>();

  const { pager, total, loading, list } = useTable<User>();
  const searchStr = ref('');

  const getData = async () => {
    try {
      loading.value = true;
      const res = await getGamePlayerList({
        ...pager.value,
        gameId: props.gameId,
        nickname: searchStr.value,
      });
      total.value = res?.data?.data?.total || 0;
      list.value = res?.data?.data?.list || [];
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = (value: string) => {
    searchStr.value = value;
    getData();
  };

  const handleRefresh = () => {
    pager.value.pageIndex = 1;
    getData();
  };

  const handleExport = async () => {
    const { close } = Notification.info('正在导出，请稍候');
    try {
      const res = await exportGamePlayer(props.gameId);
      if (res.data?.data) {
        window.open(res.data.data);
      }
    } finally {
      close();
    }
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  const router = useRouter();
  const goToUserDetail = (id: string) => {
    const routeInfo = router.resolve({
      name: 'UserDetailApp',
      query: {
        id,
      },
    });
    window.open(routeInfo.href);
  };

  const handleDeleteEnroll = (user: User) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除该报名球员？',
      onBeforeOk: async () => {
        await deleteManualGameEnroll({
          userId: user.userId,
          gameId: props.gameId,
        });
        await getData();
      },
    });
  };

  onMounted(() => {
    getData();
  });

  const addingUnreal = ref(false);
  const handleUnrealDone = (refresh: boolean) => {
    addingUnreal.value = false;
    if (refresh) {
      getData();
    }
  };

  const importing = ref(false);
  const importingCustomer = ref(false);
  const handleImportDone = (refresh: boolean) => {
    importing.value = false;
    importingCustomer.value = false;
    if (refresh) {
      getData();
    }
  };
  const showSignImportResult = ref(false);
  const signImportItemList = ref<GameSignImportItem[]>([]);
  const handleImportSuccess = (data: GameSignImportItem[]) => {
    importing.value = false;
    importingCustomer.value = false;
    getData();
    signImportItemList.value = data;
    showSignImportResult.value = true;
  };

  const manualSigning = ref(false);
  const handleManualSignDone = (refresh: boolean) => {
    manualSigning.value = false;
    if (refresh) {
      getData();
    }
  };
</script>

<template>
  <div>
    <div>
      报名情况（共{{ total }}人）

      <a-space style="margin-left: 20px">
        <a-input-search
          placeholder="搜索姓名"
          search-button
          @search="handleSearch"
        />

        <a-button @click="handleRefresh">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>

        <template v-if="game && game.gameType !== 2">
          <a-dropdown>
            <a-button>
              <template #icon><icon-download /></template>
              导出
            </a-button>
            <template #content>
              <a-doption @click="handleExport">导出全部</a-doption>
            </template>
          </a-dropdown>

          <a-button v-if="game.payWay === 1" @click="manualSigning = true">
            人工报名
          </a-button>

          <a-button v-if="!isParentGame" @click="addingUnreal = true">
            <template #icon><icon-user-add /></template>
            创建虚拟球员
          </a-button>

          <a-button v-if="game.gameType !== 1" @click="importing = true">
            <template #icon><icon-upload /></template>
            导入报名表
          </a-button>

          <a-button
            v-if="game.gameType !== 1"
            @click="importingCustomer = true"
          >
            <template #icon><icon-upload /></template>
            导入客人表
          </a-button>
        </template>
      </a-space>
    </div>

    <div style="margin-top: 20px">
      <a-spin :loading="loading" style="width: 100%">
        <table class="common-table" :cellpadding="0" :cellspacing="0">
          <tr class="common-table-row header">
            <td style="text-align: center">序号</td>
            <td>姓名</td>
            <td>性别</td>
            <td>手机号</td>
            <td>类型</td>
            <td>教练</td>
            <td>报名时间</td>
            <td>证件</td>
            <td v-if="!isParentGame">签到</td>
            <td>人工</td>
            <td style="width: 80px; text-align: center; padding: 0">操作</td>
          </tr>
          <tr v-if="list.length === 0">
            <td colspan="7">
              <a-empty />
            </td>
          </tr>
          <tr
            v-for="(user, index) in list"
            :key="user.id"
            class="common-table-row"
          >
            <td style="text-align: center">
              {{ index + 1 + (pager.pageIndex - 1) * pager.pageSize }}
            </td>
            <td>{{ user.nickname }}</td>
            <td>{{ user.sex ? '男' : '女' }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ user.ageType === 1 ? '青少年' : '成人' }}</td>
            <td>{{ user.userType === 0 ? '否' : '是' }}</td>
            <td>{{ dayjs(user.gmtUpdate).format('YYYY/MM/DD HH:mm:ss') }}</td>
            <td>{{ user.idType }}<br />{{ user.idNo }}</td>
            <td v-if="!isParentGame">
              <a-tag :color="user.sign ? 'green' : 'gray'">
                {{ user.sign ? '已签到' : '待签到' }}
              </a-tag>
            </td>
            <td>
              {{ user.manual ? '是' : '否' }}
            </td>
            <td style="width: 80px; text-align: center; padding: 0">
              <a-link
                v-if="user.userType === 0"
                @click="goToUserDetail(user.userId)"
              >
                查看
              </a-link>
              <a-link v-if="user.manual" @click="handleDeleteEnroll(user)">
                删除
              </a-link>
            </td>
          </tr>
        </table>

        <div
          v-if="total > 0"
          style="display: flex; justify-content: flex-end; margin: 12px 0 0"
        >
          <a-pagination
            size="small"
            :total="total"
            :current="pager.pageIndex"
            :page-size="pager.pageSize"
            show-total
            show-jumper
            @change="handlePageIndexChanged"
          ></a-pagination>
        </div>
      </a-spin>
    </div>

    <UnrealPlayerAdder
      v-if="addingUnreal"
      :game-id="gameId"
      @close="handleUnrealDone"
    />

    <GameSignImport
      v-if="importing"
      :game-id="gameId"
      @close="handleImportDone"
      @done="handleImportSuccess"
    />

    <GameSignImportCustomer
      v-if="importingCustomer"
      :game-id="gameId"
      @close="handleImportDone"
      @done="handleImportSuccess"
    />

    <GameSignManual
      v-if="manualSigning"
      :game-info="game"
      @close="handleManualSignDone"
    />

    <GameSignImportResult
      v-if="showSignImportResult"
      :list="signImportItemList"
      @close="
        signImportItemList = [];
        showSignImportResult = false;
      "
    />
  </div>
</template>
